function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

addLoadEvent(function() {

    function addHandlersByClassName(className, handler) {
        var buttons = document.getElementsByClassName(className);
        for (var i = 0; i < buttons.length; i++) {
            buttons[i].addEventListener('click', handler, false);
        }
    }

    function toggleHiddenShown(element) {
        if (element.className.indexOf('hidden') !== -1) {
            // This element is hidden - show it!
            element.className = element.className.replace('hidden', 'shown')
        } else if (element.className.indexOf('shown') !== -1) {
            // This element is shown - hide it!
            element.className = element.className.replace('shown', 'hidden')
        }
    }

    function toggleParentFormVisibilityHandler() {
        toggleHiddenShown(this.form);
        var addButton = this.form.getElementsByClassName('add')[0];
        toggleHiddenShown(addButton);
    }

    function promptBeforeDelete(type) {
        return function(event) {
            var answer = window.confirm('Are you sure you want to delete this ' + type + '?');
            if (!answer) {
                event = event || window.event;
                event.preventDefault ? event.preventDefault() : event.returnValue = false;
            }
        }
    }

    addHandlersByClassName('add', toggleParentFormVisibilityHandler);
    addHandlersByClassName('cancel', toggleParentFormVisibilityHandler);
    addHandlersByClassName('delete_journal_family', promptBeforeDelete('journal family'));
    addHandlersByClassName('delete_journal', promptBeforeDelete('journal'));
    addHandlersByClassName('delete_text_entry', promptBeforeDelete('entry'));
    addHandlersByClassName('delete_timeseries', promptBeforeDelete('timeseries'));
})
